package com.taotao.search.listener;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.SearchItem;
import com.taotao.common.TaotaoResult;
import com.taotao.search.mapper.SearchItemMapper;

/**
 * 消息队列的接收者：
 * @author created by wq
 * @date   Sep 3, 2017---12:50:14 AM
 * @return
 * @throws Exception<br/>
 *==========History========== <br/>
 * taotao-search-service Sep 3, 2017
 */
@Service
public class ItemAddListener implements MessageListener{

	@Autowired
	private SearchItemMapper searchItemMapper;

	//需要注入solrServer-->在applicationContext中已经配置了HttpSolrServer的单机版的bean
	@Autowired
	private SolrServer solrServer;
	/**
	 * 接收消息的业务逻辑
	 */
	@Override
	public void onMessage(Message message) {
		try {
		//在获取之前需要先强转成TextMessage
		TextMessage textMessage = (TextMessage) message;
			String text = textMessage.getText();
			Long itemId = new Long(text);
			//通过id查询到指定的商品
			SearchItem searchItem = searchItemMapper.getSearchItemByItemId(itemId);
//			SearchItem searchItem = searchItemMapper.getSearchItemByItemId(Long.parseLong(text));
			System.out.println("消费者查询到商品="+searchItem);
			//创建SolrInputDocument 文档对象
			SolrInputDocument document = new SolrInputDocument();
			document.addField("id", searchItem.getId());
			document.addField("item_title", searchItem.getTitle());
			document.addField("item_sell_point", searchItem.getSell_point());
			document.addField("item_price", searchItem.getPrice());
			document.addField("item_image", searchItem.getImage());
			document.addField("item_category_name", searchItem.getCategory_name());
			document.addField("item_desc", searchItem.getItem_desc());
			//然后将数据库查询到商品写入到索引库
			solrServer.add(document);
			//【！！！！注意：添加完成后一定要提交】
			solrServer.commit();
			System.out.println("添加的文档为="+document+searchItem.getTitle());
			//返回成功 TaoTaoResult，
			TaotaoResult.ok();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
